﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class AppLinkController : Base
{
    private readonly AppLinkService _appLinkService;
    private readonly AppLinkCateService _appLinkCateService;
    public AppLinkController(AppLinkService appLinkService, AppLinkCateService appLinkCateService)
    {
        _appLinkService = appLinkService;
        _appLinkCateService = appLinkCateService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.AppLink_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] QueryAppLink query)
    {
        List<AppLinkCate> cateList = await _appLinkCateService.GetAllListAsync("Id DESC");
        PagedInfo<ViewAppLink> pagedList = await _appLinkService.GetPageListAsync(query);
        return Success(new { data = pagedList, cateList });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.AppLink_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        List<AppLinkCate> cateList = await _appLinkCateService.GetAllListAsync("Id DESC");
        ViewAppLink data = await _appLinkService.GetEditAsync(id);
        return Success(new { data, cateList });
    }

    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.AppLink_AddOrEdit)]
    [Log(Name = "新增App链接")]
    public async Task<IActionResult> CreatePostAsync([FromBody] EditAppLink editAppLink)
    {
        AppLink appLink = editAppLink.Adapt<AppLink>();
        if (await _appLinkService.InsertReturnIdAsync(appLink) >0)
            return Success("新增App链接:" + editAppLink.Name);
        else
            return Fail("新增失败！");
    }
    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.AppLink_AddOrEdit)]
    [Log(Name = "修改App链接")]
    public async Task<IActionResult> EditPostAsync([FromBody] EditAppLink editAppLink)
    {
        AppLink model = editAppLink.Adapt<AppLink>();
        if (await _appLinkService.UpdateAsync(model) > 0)
            return Success("成功修改App链接:" + model.Name);
        else
            return Fail("修改失败！");
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.AppLink_Delete)]
    [Log(Name = "删除App链接")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _appLinkService.DeleteAsync(id) > 0)
            return Success("删除App链接 ID：" + id);
        else
            return Fail("删除失败！");
    }
}
